import BScroll from 'better-scroll';
import {Component, Output, EventEmitter, Input } from '@angular/core';

import { transformUnit } from '../../utils/basic';
import * as Constant from '../../constant/constant';
/** 借钱picker
 */
declare let document;
@Component({
  selector: 'borrow-picker',
  templateUrl: 'borrow-picker.html'
})
export class BorrowPickerComponent{

  // picker属性display绑定显示
  private pickerShow: string= null;
  // className绑定是否添加
  private addClass: boolean= false;
  // 一次性定时器,处理display和过渡动画冲突
  private timer: any = null;

  // 关联数据
  private data: any;

  // picker元素集合
  private pickerElem;
  // wheel元素集合
  private wheelElem;

  // 默认选中的下标索引数组(0:第一列,1代表第二列)
  private selectedIndex= [];
  // 保存的scroll的数组
  private wheels= [];

  @Input() options: any= {};
  // 确定后返回数组
  @Output() selectedVal= new EventEmitter<any>();
  @Output() cancelEvent= new EventEmitter<any>();
  constructor() {}

  ngOnInit() {}

  // 组件输入属性值发生改变（首次调用一定会发生在 ngOnInit之前。）
  ngOnChanges(){
    if(typeof this.options === 'undefined') return;
    this.initInputList();
    this.initSelectedIndex();
    this.pickerElem = document.querySelectorAll('.picker')[0];
    this.wheelElem = this.pickerElem.getElementsByClassName('wheel-hook');
    this.bindEvent();
  }

  /*** 处理后台返回数据,映射到picker中
  * */
  private initInputList(): void
  {
    const config= this.options.config;
    let newSet= new Set();
    const newConfig= config.map((value,index)=>
    {
      // 初始化sub 和 type
      let sub= [], type;
      const name= transformUnit(value.name, Constant.AMOUNT_PREFIX,0);
      type= value.type;
      if(value.hasOwnProperty('sub'))
      {
        value.sub.forEach(item=>{
          newSet.add(item);
          const name= transformUnit(item, Constant.TIMELINIT_POSTFIX,String(item).length);
          const value= index;
          sub.push({name, value})
        });
      }
      return {name, sub, type};
    });
    const arr= Array.from(newSet).sort((a,b)=> a-b); // 升序
    const newArr= arr.map((item,index)=>{
      let value= index;
      const name= transformUnit(item, Constant.TIMELINIT_POSTFIX,String(item).length);
      return { name, value };
    });
    this.data= [];
    this.data.push(newConfig);
    this.data.push(newArr);
  }

   /*** 初始化选中的下标数组
  * */
  initSelectedIndex(): void
   {
    if (this.options.selectedIndex) {
       this.selectedIndex = this.options.selectedIndex;
    } else {
      for (let i = 0; i < this.data.length; i++) {
        this.selectedIndex[i] = 0;
      }
    }
  }

  /*** 绑定监听事件
  * */
  addEventLister(el, type, fn, capture= false): void
  {
    el.addEventListener(type, fn, capture);
  }
  /*** 绑定事件
   * */
  bindEvent(): void
  {
    this.addEventLister(this.pickerElem, 'touchmove', (e) => {
      e.preventDefault();
    });
  }

  /*** 创建二级list
  * */
  createList(obj, list): void
  {
    obj.forEach(function(item, index){
      const name= item.name;
      const value= item.index;
      list.push({ name, value});
    })
  }

  /*** 触发picker修改
   * @param index 移动列
   * @param selectedIndex 列下标
  * */
  triggerPickerChange(index,selectedIndex): void
  {
    if (index !== 0) return;
    let second = [];
    const targetList = this.data[0][selectedIndex];
    if (targetList.hasOwnProperty('sub')) {
      this.createList(targetList.sub, second);
    } else {
      second = [{name: '', value: 0}];
    }
    this.data[1] =[...second];
    this.selectedIndex[1] = second.length-1;

    // 此处,模板渲染慢于BScroll,出现二级无法滑动bug,使用定时器处理
    setTimeout(()=>{
      this.createWheel();
    },0);
  }

   /*** 显示picker
  * */
  show() {
    this.pickerShow = 'block';
    this.clearTime();

    this.timer= setTimeout(()=>{
      this.addClass = true;

      this.createWheel();

    },30);
  }

  /*** 渲染BScroll
   * */
  createWheel(): void
  {
    this.wheels = [];
    for (let i = 0; i < this.data.length; i++) {
      this.wheels[i] = new BScroll(this.wheelElem[i], {
        wheel: true,
        // selectedIndex: this.selectedIndex[i] 移除
      });
      // 为每个绑定事件
      this.wheels[i].on('scrollEnd', () => {
        let currentIndex = this.wheels[i].getSelectedIndex();
        if (this.selectedIndex[i] !== currentIndex) {
          this.selectedIndex[i] = currentIndex;
          this.triggerPickerChange(i, currentIndex);
        }
      });
    }
    this.goSelectIndex();
  }
   /*** 跳到指定的数组
   * */
  goSelectIndex(): void
   {
    for (let i = 0; i < this.data.length; i++) {
      this.wheels[i].enable();
      this.wheels[i].wheelTo(this.selectedIndex[i]);
    }
  }

  /*** 隐藏picker
   * */
  hide(): void
  {
    this.addClass = false;
    this.clearTime();
    this.timer = setTimeout(()=>{
      this.pickerShow = null;
      for (let i = 0; i < this.data.length; i++) {
        this.wheels[i].disable();
      }
    },500);
    this.emitPickerCancel();
  }

  /*** 离开
   * */
  emitPickerCancel(): void
  {
    this.cancelEvent.emit();
  }
  /** 清除定时器
  * */
  clearTime(): void
  {
    if(this.timer){
      clearTimeout(this.timer);
      this.timer= null;
    }
  }

  /*** 确定操作
   * */
  executeConfirm(): void
  {
    this.hide();
    let selectedVal = [];
    for (let i = 0; i < this.data.length; i++) {
      let index = this.wheels[i].getSelectedIndex();
      // 保存下标一样
      if(this.selectedIndex[i] === index){
        selectedVal[i] = this.data[i][index].name;
      }else{
        let sIndex = this.selectedIndex[i];
        selectedVal[i] = this.data[i][sIndex].name;
      }
    }
    this.emitPickerSelect(selectedVal);

  }
  /*** 发送选中的数组
   * @param selectedVal 选中的数组
   * @return object { amount: '金额', timeLimit: '期限'}
   * */
  emitPickerSelect(selectedVal): void
  {
    const amount=transformUnit(selectedVal[0], Constant.AMOUNT_PREFIX);
    const timeLimit=transformUnit(selectedVal[1], Constant.TIMELINIT_POSTFIX);
    this.selectedVal.emit({
      value: {amount, timeLimit}
    });
  }


}
